package foundation;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ?
 * @version 1.00
 */
public class FConfigFile {
	String fileName;
	File file;
	
	/**
	 * @param fileName  the name of the configuration file. The file will be
	 * created if it doesn't exist.
	 */
	public FConfigFile(String fileName) {
		this.fileName = fileName;
		try {
			file = new File(fileName);
			file.createNewFile();
		} catch (IOException e) {}
	}
	
	/**
	 * @param parameter  the parameter to find in the configuration file
	 * @return the value of the parameter
	 */
	public String getParameter(String parameter) {
		String value = null;
		Pattern pattern = Pattern.compile(" *" 
				+ parameter.toLowerCase() + " +([^ ]*)");

		try {
			Scanner in = new Scanner(file);
			String currentLine;
			Matcher matcher;

			while(in.hasNext()) {
				currentLine = in.nextLine().trim();
				matcher = pattern.matcher(currentLine);
				if (matcher.matches()) {
					value = matcher.group(1);
					break;
				}
			}

			in.close();

		} catch (FileNotFoundException e) { }

		return value;
	}
	
	/**
	 * @param parameter the parameter to set in the configuration file
	 * @param value the value of the parameter
	 */
	public void setParameter(String parameter, String value) 
									throws FileNotFoundException, IOException {
		Pattern pattern = Pattern.compile(" *"+ parameter.toLowerCase() + " +[^ ]*");

		File tempFile = new File("temp.txt");
		tempFile.createNewFile();
		FileWriter out = new FileWriter(tempFile);
		PrintWriter output = new PrintWriter(out);

		Scanner input = new Scanner(file);
		String currentLine;
		Matcher matcher;
		boolean matched = false;

		while (input.hasNext()) {
			currentLine = input.nextLine();
			matcher = pattern.matcher(currentLine);
			if (matcher.matches()) {
				output.println(parameter.toLowerCase() + " " + value);
				matched = true;
			} else {
				output.println(currentLine);
			}
		}

		if (!matched) {
			output.println(parameter.toLowerCase() + " " + value);
		}

		input.close();
		output.close();

		//Remove old file:
		file.delete();
		tempFile.renameTo(file);
	}
}
